package org.zebra.satoken;

import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.StpLogic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.zebra.cache.config.CacheConfig;
import org.zebra.common.core.GeneralYmlPropertySourceFactory;
import org.zebra.satoken.security.SecurityConfig;
import org.zebra.satoken.security.SecurityProperties;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.Parameter;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * @author zhanghongbin
 */
@AutoConfiguration(after = CacheConfig.class)
@Import(SecurityConfig.class)
@PropertySource(value = "classpath:satoken-springboot.yml", factory = GeneralYmlPropertySourceFactory.class)
public class SaTokenConfig {

    public static final String tokenHeaderName = "Authorization";

    /**
     * Sa-Token 整合 jwt (Simple 简单模式)
     *
     * @return 对象
     */
    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }

    /**
     * 自定义redis存储
     *
     * @return 对象
     */
    //    @Bean
    //    @ConditionalOnMissingBean
    //    public SaTokenDao saTokenDao(@Autowired RedisTemplate<String, Object> redisTemplate) {
    //        return new SaTokenDaoRedisPlus(
    //                RedisUtil.createStringRedisTemplate(),
    //                RedisUtil.createRedisTemplate(RedisSerializer.string(), redisTemplate.getValueSerializer()));
    //    }
    @Bean
    @ConditionalOnMissingBean(value = SaTokenExceptionAdvice.class)
    public SaTokenExceptionAdvice saTokenExceptionAdvice() {
        return new SaTokenExceptionAdvice();
    }

    @ConditionalOnClass(Docket.class)
    static class Swagger {
        @Bean
        public Parameter swaggerTokenParameter(@Autowired SecurityProperties securityProperties) {
            ParameterBuilder tokenPar = new ParameterBuilder();
            tokenPar.name(tokenHeaderName)
                    .description("认证 Token")
                    .modelRef(new ModelRef("string"))
                    .parameterType("header")
                    .required(true);
            if (securityProperties.getMockEnabled()) {
                tokenPar.defaultValue("Bearer test");
            }
            return tokenPar.build();
        }
    }
}
